package mes.kanban.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import mes.kanban.config.KVRedisConfig;
import mes.kanban.entity.CustomerCompany;
import mes.kanban.service.CustomerCompanyServiceI;
import mes.kanban.vo.AjaxReturnVO;
import mes.kanban.vo.MesUserVO;

@Controller
@RequestMapping(value="/customerCompany")
public class CustomerCompanyController {
	
	@Autowired
	private CustomerCompanyServiceI customerCompanyServiceI;
	
	
	@GetMapping(value="/toList")
	public String returnCustomerCompanyPage(HttpServletRequest req,Model model) {
		
		return "customerCompany/company";
	}
	
	@GetMapping(value="/getCompanyDetail")
	@ResponseBody
	public AjaxReturnVO returnCustomerCompanyMessage(HttpServletRequest req) {
		
		AjaxReturnVO vo = new AjaxReturnVO();
		
		try {
			HttpSession session = WebUtils.toHttp(req).getSession();
			
			Object info = session.getAttribute(KVRedisConfig.SESSION_ATTRIBUTE_USER.getHaskey());
			MesUserVO userInfo = new MesUserVO();
			BeanUtils.copyProperties(info, userInfo);
			
			CustomerCompany cc = this.customerCompanyServiceI.findOrSaveById(userInfo.getUserCode());
			
			List<CustomerCompany> ccs = new ArrayList<CustomerCompany>();
			ccs.add(cc);
			
			vo.setOk(true);
			vo.setData(ccs);
			
		} catch (Exception e) {
			e.printStackTrace();
			vo.setFail(vo, e.getMessage());
		}
		
		return vo;
		
	}
	
	@PostMapping("/updateCompanyDetail")
	@ResponseBody
	public AjaxReturnVO updateCompanyDetail(@RequestBody CustomerCompany pany) {
		
		AjaxReturnVO vo = new AjaxReturnVO();
		
		try {
			
			vo.setOk(true);
			this.customerCompanyServiceI.updateCustomerConpany(pany);
			
		} catch (Exception e) {
			e.printStackTrace();
			vo.setFail(vo, e.getMessage());
		}
		
		return vo;
	}

}
